package com.graduation.check.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.*;

@Slf4j
@Service
public class AliBailianService {

    @Value("${aliyun.bailian.api-key:}")
    private String apiKey;

    private final WebClient webClient;
    private final ObjectMapper objectMapper;

    public AliBailianService(@Value("${aliyun.bailian.api-key:}") String apiKey) {
        this.objectMapper = new ObjectMapper();

        WebClient.Builder webClientBuilder = WebClient.builder()
                .baseUrl("https://dashscope.aliyuncs.com")
                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);

        if (apiKey != null && !apiKey.trim().isEmpty()) {
            webClientBuilder.defaultHeader("Authorization", "Bearer " + apiKey);
            log.info("阿里云百炼API密钥已配置");
        } else {
            log.warn("阿里云百炼API密钥未配置，请检查配置文件");
        }

        this.webClient = webClientBuilder.build();
    }

    /**
     * 调用通义千问模型
     */
    public String callQwenModel(String prompt) {
        try {
            log.info("开始调用阿里云百炼API，提示词长度: {}", prompt.length());

            if (apiKey == null || apiKey.trim().isEmpty()) {
                throw new RuntimeException("阿里云百炼API密钥未配置");
            }

            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "qwen-plus");

            Map<String, Object> input = new HashMap<>();
            Map<String, Object> message = new HashMap<>();
            message.put("role", "user");
            message.put("content", prompt);

            input.put("messages", Collections.singletonList(message));
            requestBody.put("input", input);

            Map<String, Object> parameters = new HashMap<>();
            parameters.put("result_format", "text");
            parameters.put("max_tokens", 4000);
            parameters.put("temperature", 0.1);
            requestBody.put("parameters", parameters);

            log.debug("发送请求到阿里云百炼API");
            String response = webClient.post()
                    .uri("/api/v1/services/aigc/text-generation/generation")
                    .bodyValue(requestBody)
                    .retrieve()
                    .onStatus(status -> status.is4xxClientError() || status.is5xxServerError(),
                            clientResponse -> {
                                log.error("API调用失败，状态码: {}", clientResponse.statusCode());
                                return Mono.error(new RuntimeException("API调用失败，状态码: " + clientResponse.statusCode()));
                            })
                    .bodyToMono(String.class)
                    .block();

            log.info("阿里云百炼API调用成功");
            return parseResponse(response);

        } catch (Exception e) {
            log.error("调用阿里云百炼API失败", e);
            throw new RuntimeException("AI服务调用失败: " + e.getMessage());
        }
    }

    /**
     * 解析API响应 - 修复版
     */
    private String parseResponse(String response) {
        try {
            log.debug("开始解析API响应");
            Map<String, Object> responseMap = objectMapper.readValue(response, Map.class);

            // 调试：打印完整的响应结构
            log.debug("完整的API响应结构: {}", responseMap);

            // 方法1: 检查是否有output.text字段（新格式）
            if (responseMap.containsKey("output")) {
                Map<String, Object> output = (Map<String, Object>) responseMap.get("output");

                // 检查是否有text字段
                if (output.containsKey("text")) {
                    String textContent = (String) output.get("text");
                    log.debug("从output.text提取内容成功");
                    return textContent.trim();
                }

                // 方法2: 检查是否有choices字段（旧格式）
                if (output.containsKey("choices")) {
                    List<Map<String, Object>> choices = (List<Map<String, Object>>) output.get("choices");
                    if (choices != null && !choices.isEmpty()) {
                        Map<String, Object> firstChoice = choices.get(0);
                        if (firstChoice.containsKey("message")) {
                            Map<String, Object> message = (Map<String, Object>) firstChoice.get("message");
                            String content = (String) message.get("content");
                            log.debug("从choices.message.content提取内容成功");
                            return content;
                        }
                    }
                }
            }

            // 方法3: 如果标准解析都失败，尝试直接返回整个响应的字符串表示
            log.warn("无法通过标准方式解析响应，尝试直接返回响应内容");
            return response;

        } catch (Exception e) {
            log.error("解析API响应失败", e);
            throw new RuntimeException("解析AI响应失败: " + e.getMessage());
        }
    }
}